import { Base64 } from 'js-base64'
import md5 from 'js-md5'
let u = navigator.userAgent;
let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
export const detaMixin = {
  methods: {
    data() {
      return {
        customerId: null,
        tokenStr: null,
      }
    },
    isLogin() {
      return new Promise((resolve, reject) => {
        BmacJSBridge.call(
          "getAPDataStorage",
          {
            //获取登录信息
            type: "common",
            business: "userInfoGrid",
            key: "userInfo",
          },
          (result) => {
            if (
              result.error == "11"
            ) {
              BmacJSBridge.call(
                "startApp",
                {
                  appId: "00000060",
                  closeCurrentApp: true,
                  popNum: '-1',
                  type: "1"
                }, (result) => {
                });

            } else { //登录啦
              resolve(true)
            }
          }
        );
      })
    },
    changeAccount() {
      return new Promise((resolve, reject) => {
        //获取当前时间的时间戳
        let now = new Date().valueOf();
        //第一次点击
        if (this.lastTime == 0) {
          console.log('触发事件');
          this.lastTime = now;
          resolve()
        } else {
          if ((now - this.lastTime) > 1500) {
            //重置上一次点击时间，1500是我自己设置的2秒间隔，根据自己的需要更改
            this.lastTime = now;
            console.log('间隔大于1.5秒，触发方法');
            //添加自己要调用的方法
            resolve()
          } else {
            console.log('不触发');
          }
        }
      })
    },
    _getUserInfoData() { // 获取用户信息，没有登录并跳转登录
      return new Promise((resolve, reject) => {
        BmacJSBridge.call(
          "getAPDataStorage",
          {
            //获取登录信息
            type: "common",
            business: "userInfoGrid",
            key: "userInfo",
          },
          (result) => {
            console.log(result);
            if (
              result.error == "11"
            ) {
              BmacJSBridge.call(
                "startApp",
                {
                  appId: "00000060",
                  closeCurrentApp: true,
                  popNum: '-1',
                  type: "1"
                }, (result) => {
                });

            } else { //登录啦
              let userInfo = JSON.parse(result.data).data;
              let customerId = userInfo.customerId;
              this.customerId = customerId
              let userLoginId = userInfo.logonIds;
              let userMobile = userInfo.mobileNo;
              let tokenStr = userInfo.token_type + " " + userInfo.access_token;
              this.tokenStr = tokenStr
              let userInfoData = {
                customerId: customerId,
                userLoginId: userLoginId,
                userMobile: userMobile,
                tokenStr: tokenStr,
              }
              resolve(userInfoData)
            }
          }
        );
      })
    },

    adverHref(obj, eventID) { // 广告点击跳转
      this.changeAccount().then(res => {
        let clickData = {
          adresourcesId: obj.adresourcesId,
          adpositionId: obj.adpositionId,
          adpositionName: obj.adpositionName,
          imei: this.sliderHttp.imei,
          type: '1',
        }
        console.log(clickData)
        //
        let base = Base64.encode(JSON.stringify(clickData))
        let md5Base = md5(base + this.sliderHttp.sjRandomKey)
        let getAdveObj = JSON.stringify({
          "object": base,
          "sign": md5Base
        })
        this.$ajax({ // 点击量请求
          method: "post",
          url: this.sliderHttp.repPathUrl + "advertising/clickrate",
          data: getAdveObj,
          headers: {
            'content-type': 'application/json',
            'Authorization': "Bearer " + this.sliderHttp.tokenStr
          },
        }).then(res => {
          // 不管成功与否，走下面埋点并跳转
        })
        console.log('广告数据', obj)
        if (obj.type == 1) { //商城
          this.toShoppingUrlAdver(obj, this.sliderHttp)
        } else if (obj.type == 2) { //不跳转
          return
        } else if (obj.type == 5) { //微信小程序
          this.toWXLaunchMiniProgramAdver(obj)
        } else if (obj.type == 6) { //支付宝小程序
          this.toYKTLaunchMiniProgramAdver(obj)
        } else if (obj.type == 7) { //跳转离线包
          this.toStartApp(obj)
        } else { // 其他统一跳转Url
          this.pushUrl(obj)
        }
      })

    },
    toShoppingUrlAdver(a, b) { // a广告数据，b签名接口
      this._getUserInfoData().then(userResult => {
        const toNeteaseUrl = {
          channelCode: a.channelCode,
          extendParam: userResult.userLoginId,
          extUserId: userResult.customerId, // 用户唯一标识
          position: 'home',
          moduleCode: a.channelCode == 'bjyikatong' || 'bjykt_yanxuan' ? 'you163shop' : '',
        };
        console.warn('参数', toNeteaseUrl)
        BmacJSBridge.call("encryptDataWithRSA3", toNeteaseUrl, (resultEncrypt) => {
          var datas = resultEncrypt.encryptedData;
          this.$ajax({
            method: "post",
            url: this.sliderHttp.thirdPayOrderSign,
            data: datas,
            headers: {
              'Content-Type': 'application/json',
              'Authorization': this.sliderHttp.authorizations,
            },
          }).then(resultSign => {
            BmacJSBridge.call("decryptDataWithRSA3", { decryptParam: resultSign.data }, (databut) => {
              const request = JSON.parse(databut.encryptedData);
              console.warn('商城签名', request)

              let toNeteaseUrllink = `${a.shopUrl}?channelCode=${toNeteaseUrl.channelCode}&extUserId=${userResult.customerId}&extendParam=${userResult.userLoginId}&position=${toNeteaseUrl.position}&timestamps=${request.timestamps}&sign=${request.sign.toUpperCase()}&version=4`
              console.warn(toNeteaseUrllink)
              BmacJSBridge.call('startApp', {
                url: toNeteaseUrllink, // 要打开页面的 URL
                // 打开页面的配置参数
                readTitle: true,    //自动读取 title
                showOptionMenu: false,    // 隐藏右边菜单
                // 用于给新开的页面传递参数，可选
                // 在新开的页面使用 BmacJSBridge.startupParams 可以获取到 passData
                passData: {
                  key1: "key1Value",
                  key2: "key2Value"
                },
                type: "2"
              });
            })

          })
        })

      })
    },

    pushUrl(a) {
      BmacJSBridge.call('startApp', {
        url: a.adresourcesUrl, // 要打开页面的 URL
        // 打开页面的配置参数
        readTitle: true,    //自动读取 title
        showOptionMenu: false,  // 隐藏右边菜单
        // 用于给新开的页面传递参数，可选
        // 在新开的页面使用 BmacJSBridge.startupParams 可以获取到 passData
        passData: {
          key1: "key1Value",
          key2: "key2Value"
        },
        type: "2"
      });
    },
    toStartApp(a) {
      BmacJSBridge.call('startApp', {
        appId: a.adresourcesUrl,
        passData: {
          info: JSON.stringify(a)
        },
        type: "2"
      }, (result) => {
      });
    },
    toYongJunKa() {
      console.log("---go拥军卡");
      BmacJSBridge.call('openSupportSoldierCard')
    },
    toYKTLaunchMiniProgramAdver(a) {
      BmacJSBridge.call('startApp', {
        appId: a.adresourcesUrl,
        passData: {},
        msg: '首页跳转主题',
        type: "3"
      }, (result) => {
      });
    },
    toWXLaunchMiniProgramAdver(a) {
      BmacJSBridge.call('toWXLaunchMiniProgram', {
        userName: a.adresourcesName,
        reqPath: a.adresourcesUrl,
      })
    },
    // 卡券-通过路由跳转
    toBagListTicket() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          this.$router.push({
            path: '/cardBag',
          })
        })
      })
    },

    pasteCardRecharge() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          this.$emit('closepop', false)
          let embedding = {
            eventID: "pasteCardRecharge", //商品ID
            extra: {
              name: '首页贴卡充值'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call('skipToTopUp', {
              // pageId: '00000009',
              // isNFC: true,
              // params: JSON.stringify(params),
              // title: '贴卡充值',
              // rightMenu: '卡类型查询',
              // rightUrlORpageId: 'https://ios.bmac.com.cn:29100/bmac_clientwap/bmac/page-tkcz-zcklx.html',
              // h5UrlTitle: '可支持的卡类型',
              businessType: "13"
            })
          })
        })

      })
    },
    electronicInvoice() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "electronicInvoice", //商品ID
            extra: {
              name: '首页电子发票'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call('openElectronicInvoice');
          })
        })
      })
    },
    toAndroidTheme() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "androidThemeEntry", //商品ID
            extra: {
              name: '安卓主题入口'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call('startApp', {
              appId: '__UNI__ECB5F91',
              msg: '更多跳转主题',
              type: "3"
            }, (result) => {
            });
          })
        })
      })
    },
    jfStore(shopUrl) {
      this.changeAccount().then(res2 => {
        this._getUserInfoData().then(userResult => {
          const toNeteaseUrl = {
            channelCode: 'yikatong_bmac',
            extendParam: userResult.userLoginId,
            extUserId: userResult.customerId, // 用户唯一标识
            position: 'home',
            moduleCode: '',
          };
          BmacJSBridge.call("encryptDataWithRSA3", toNeteaseUrl, (resultEncrypt) => {
            var datas = resultEncrypt.encryptedData;
            this.$ajax({
              method: "post",
              url: this.thirdPayOrderSign,
              data: datas,
              headers: {
                'Content-Type': 'application/json',
                'Authorization': this.authorizations,
              },
            }).then(resultSign => {
              BmacJSBridge.call("decryptDataWithRSA3", { decryptParam: resultSign.data }, (databut) => {
                const request = databut.encryptedData;

                let toNeteaseUrllink = `${shopUrl}channelCode=${toNeteaseUrl.channelCode}&extUserId=${userResult.customerId}&extendParam=${userResult.userLoginId}&position=${toNeteaseUrl.position}&timestamps=${request.timestamps}&sign=${request.sign.toUpperCase()}&version=4`
                console.warn(toNeteaseUrllink)
                BmacJSBridge.call('startApp', {
                  url: toNeteaseUrllink, // 要打开页面的 URL
                  // 打开页面的配置参数
                  readTitle: true,    //自动读取 title
                  showOptionMenu: false,    // 隐藏右边菜单
                  // 用于给新开的页面传递参数，可选
                  // 在新开的页面使用 BmacJSBridge.startupParams 可以获取到 passData
                  passData: {
                    key1: "key1Value",
                    key2: "key2Value"
                  },
                  type: "2"
                });
              })

            })
          })

        })
      })

    },
    handleClick() { //交易记录
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "Transactions", //商品ID
            extra: {
              name: '首页交易记录'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call(
              "startApp",
              {
                appId: "00000006",
                passData: {
                  // publicId: 'xxxxxx',
                  readTitle: true, //自动读取 title
                },
                closeCurrentApp: false,
                type: '1',
                url: '/bmac/index.html#/tradeRecord',
              },
              function (result) {
                // noop
              }
            );
          })
        })
      })
    },
    shopStore() { // 跳转旗舰店
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "shopStore", //商品ID
            extra: {
              name: '首页旗舰店'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call('startApp', {
              url: 'https://bmac.tmall.com', // 要打开页面的 URL
              // 打开页面的配置参数
              defaultTitle: "旗舰店",
              readTitle: true,    //自动读取 title
              showOptionMenu: false,    // 隐藏右边菜单
              // 用于给新开的页面传递参数，可选
              // 在新开的页面使用 BmacJSBridge.startupParams 可以获取到 passData
              passData: {
                key1: "key1Value",
                key2: "key2Value"
              },
              type: '2'
            });
          })
        })

      })
    },
    toOnLine() { // 跳转到在线客服
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "online", //商品ID
            extra: {
              name: '更多在线客服'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            BmacJSBridge.call('toOnLineServiceUrlAndTitle')
          })

        })

      })
    },
    cardTimeUp() {  // 卡片延期
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "cardTimeUp", //商品ID
            extra: {
              name: '更多页特种卡延期'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            // BmacJSBridge.call('toCardTimeUp')
            let params = {}

            BmacJSBridge.call('skipToTopUp', {
              cardInfo: params,
              businessType: "6"
            })
          })
        })
      })
    },
    toChangeCode() { // 充值码充值
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          let embedding = {
            eventID: "homeRechargeCode", //商品ID
            extra: {
              name: '首页充值码'
            },
          }
          BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
            let u = navigator.userAgent;
            let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if (isiOS) {
              BmacJSBridge.call('startApp', {
                appId: '00000069',
                passdata: {},
                msg: '首页跳转充值码',
                type: "1"
              }, (result) => {
                console.warn(result)
              });
            } else {
              BmacJSBridge.call('nfcCardTouch', {
                pageId: '00000073',
                // url: "http://192.168.120.44:8081",
                isNFC: true,
                params: {},
                title: '充值码',
                rightMenu: '使用帮助',
                rightUrlORpageId: 'https://ios.bmac.com.cn:29100/bmac_clientwap/bmac/page-czm-sysm/page-czm-sysm.html',
                h5UrlTitle: '使用说明',
              })
            }
          })
        })
      })
    },

    // 学生卡查询(路由跳转)
    toStudentCardSearch() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          this.$router.push({
            path: '/studentCardSearch',
          })

        })
      })
    },

    topecialSCard() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          BmacJSBridge.call('startApp', {
            appId: '00001007',
            msg: '特种卡',
            type: "1"
          }, (result) => {
            console.warn(result)
          });
        })
      })
    },
    toDivestment() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          this.$router.push({
            path: '/queryOrderNum',
          })
        })
      })
    },
    toParkList() {
      BmacJSBridge.call('startApp', {
        appId: '00001018',
        passdata: {},
        msg: '年票预约',
        type: "1",
        url:'/bmac/index.html#/advanceParkList'
      }, (result) => {
        console.warn(result)
      });
    },
    toParkRealName() {
      BmacJSBridge.call('startApp', {
        appId: '00001018',
        passdata: {},
        msg: '公园年票',
        type: "1"
      }, (result) => {
        console.warn(result)
      });
    },
    toLinkHref(href) {
      this.changeAccount().then(res => {
        this._getUserInfoData().then(userInfo => {
          let userInfoStr = `?source=1&customerId=${userInfo.customerId}&logonIds=${userInfo.userLoginId}&mobileNo=${userInfo.userMobile}&tokenStr=${userInfo.tokenStr}`
          console.log(`${href}${userInfoStr}`)
          if (isiOS) { // ios
            BmacJSBridge.call('startApp', {
              url: `${href}${userInfoStr}`, // 要打开页面的 URL
              // 打开页面的配置参数
              passData: {},
              readTitle: true,    //自动读取 title
              showOptionMenu: false,   // 隐藏右边菜单
              type: "2"
            });
          } else {
            BmacJSBridge.call('nfcCardTouch', {
              pageId: '',
              url: `${href}${userInfoStr}`,
              isNFC: false,
              params: {},
            })
          }


        })
      })

    },

    // 企业员工卡-通过原生方法
    toQYCard() {
      this.changeAccount().then(res => {
        this.isLogin().then(res => {
          // 获取登录信息
          BmacJSBridge.call('getAPDataStorage', {
            type: "common",
            business: "userInfoGrid",
            key: "userInfo",
          }, (result) => {
            if (result.error == '11') {
              BmacJSBridge.call(
                "startApp",
                {
                  appId: "00000060",
                  closeCurrentApp: true,
                  popNum: '-1',
                  type: '1'
                }, (result) => {
                });
            } else {
              let userInfostr = JSON.parse(result.data)
              let userInfoData = userInfostr.data
              console.log('用户信息')
              if (userInfoData.userType !== '2' && userInfoData.userType !== '7') {
                BmacJSBridge.call(
                  "startApp",
                  {
                    appId: "00000063",
                    passData: {
                      startSource: '1'
                    },
                    url: "/bmac/index.html#/setPayPassword",
                    type: "1"
                  },
                  (result) => {
                    // noop
                  }
                );
              } else {
                this.$router.push({
                  path: '/staffCard',
                })
              }

            }
          })

        })
      })
    },
    toMinSheng() {
      // var _this = this;
      let data = {
        customerId: this.customerId,
        busiType: "1",
      }
      console.log(data, "请求参数");
      console.log(this.tokenStr);
      console.log(this.authorizations);
      BmacJSBridge.call(
        "startApp",
        {
          appId: "00001014",
          type: '1'
        },
        (result) => {
          // noop
        }

      )
    },
    //跳转穿戴设备
    toWearDevice() {
      BmacJSBridge.call('startApp', {
        appId: '00001025',
        passData: {},
        type: "1"
      }, (result) => {
      });
    }
  },
}
